package com.chatplus.application.controller.admin.biz;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatplus.application.common.domain.response.SensitiveWordFilterResultResponse;
import com.chatplus.application.common.event.EventPubSub;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.page.PageParam;
import com.chatplus.application.dao.basedata.SensitiveWordDao;
import com.chatplus.application.domain.entity.basedata.SensitiveWordEntity;
import com.chatplus.application.domain.notification.ReloadSensitiveWordsEvent;
import com.chatplus.application.domain.request.SensitiveWordRequest;
import com.chatplus.application.domain.response.PlusPageResponse;
import com.chatplus.application.domain.response.SensitiveWordResponse;
import com.chatplus.application.service.basedata.SensitiveWordService;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.time.Instant;
import java.util.List;

@RestController
@RequestMapping("/api/admin/sensitiveWord")
@Tag(name = "敏感词API", description = "敏感词API")
public class SensitiveWordController {

    private final SensitiveWordService sensitiveWordService;
    private final SensitiveWordDao sensitiveWordDao;
    private final EventPubSub<Serializable> eventPublisher;

    @Autowired
    public SensitiveWordController(SensitiveWordService sensitiveWordService
            , SensitiveWordDao sensitiveWordDao
            , EventPubSub<Serializable> eventPublisher) {
        this.sensitiveWordService = sensitiveWordService;
        this.sensitiveWordDao = sensitiveWordDao;
        this.eventPublisher = eventPublisher;
    }

    @RequestMapping("filter")
    public SensitiveWordFilterResultResponse filter(String input) {
        return sensitiveWordService.filter(input);
    }

    @PostMapping("/list")
    @Operation(summary = "后台敏感词分页列表")
    public PlusPageResponse<SensitiveWordResponse> list(@RequestBody SensitiveWordRequest plusPageRequest) {
        PageParam pageParam = new PageParam(plusPageRequest.getPage(), plusPageRequest.getPageSize());
        LambdaQueryWrapper<SensitiveWordEntity> queryWrapper =
                Wrappers.<SensitiveWordEntity>lambdaQuery()
                        .like(StringUtils.isNotBlank(plusPageRequest.getWord()), SensitiveWordEntity::getWord, plusPageRequest.getWord())
                        .like(StringUtils.isNotBlank(plusPageRequest.getRemark()), SensitiveWordEntity::getRemark, plusPageRequest.getRemark())
                        .isNull(SensitiveWordEntity::getDeletedAt)
                        .orderByDesc(SensitiveWordEntity::getCreatedAt);
        Page<SensitiveWordEntity> pageDTO = sensitiveWordService.page(pageParam.toPage(), queryWrapper);
        List<SensitiveWordEntity> orderEntityList = pageDTO.getRecords();
        if (CollUtil.isEmpty(orderEntityList)) {
            return new PlusPageResponse<>(plusPageRequest.getPage(), plusPageRequest.getPageSize(), 0, 0, Lists.newArrayList());
        }
        List<SensitiveWordResponse> responseList = orderEntityList.stream().map(SensitiveWordResponse::build).toList();
        return new PlusPageResponse<>(pageParam.getCurrent(), pageParam.getSize()
                , pageDTO.getPages(), pageDTO.getTotal(), responseList);
    }

    @PostMapping("containsSensitiveWord")
    public SensitiveWordFilterResultResponse containsSensitiveWord(@RequestBody SensitiveWordFilterResultResponse input) {
        SensitiveWordFilterResultResponse response = new SensitiveWordFilterResultResponse();
        if (input == null || StringUtils.isBlank(input.getInput())) {
            return response;
        }
        SensitiveWordFilterResultResponse resultVo = sensitiveWordService.filter(input.getInput());
        if (resultVo != null) {
            boolean contains = CollectionUtils.isNotEmpty(resultVo.getSensitiveWordList());
            response.setInput(input.getInput());
            response.setContainsSensitiveWord(contains);
        }
        return response;
    }

    @PostMapping("save")
    public SensitiveWordResponse save(@RequestBody SensitiveWordResponse vo) {
        if (vo == null || StringUtils.isBlank(vo.getWord())) {
            throw new BadRequestException("参数不可为空");
        }
        vo.setWord(StringUtils.trimToEmpty(vo.getWord()));

        LambdaQueryWrapper<SensitiveWordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SensitiveWordEntity::getWord, vo.getWord());

        List<SensitiveWordEntity> entityList = sensitiveWordDao.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(entityList)) {
            for (SensitiveWordEntity entity : entityList) {
                entity.setDeletedAt(null);
                sensitiveWordDao.updateById(entity);
            }
        } else {
            SensitiveWordEntity entity = new SensitiveWordEntity();
            entity.setWord(vo.getWord());
            entity.setRemark(vo.getRemark());
            sensitiveWordDao.insert(entity);
        }
        eventPublisher.publish(new ReloadSensitiveWordsEvent());
        return vo;
    }

    @PostMapping("remove")
    public void remove(String word) {
        if (StringUtils.isBlank(word)) {
            throw new BadRequestException("参数不可为空");
        }
        LambdaQueryWrapper<SensitiveWordEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SensitiveWordEntity::getWord, word);

        List<SensitiveWordEntity> entityList = sensitiveWordDao.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(entityList)) {
            for (SensitiveWordEntity entity : entityList) {
                if (entity.getDeletedAt() == null) {
                    entity.setDeletedAt(Instant.now());
                    sensitiveWordDao.updateById(entity);
                }
            }
        }
        eventPublisher.publish(new ReloadSensitiveWordsEvent());
    }


}
